package com.zst.bluetooth.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.baidu.mobstat.StatService;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.litesuits.orm.db.assit.QueryBuilder;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;
import com.zst.bluetooth.R;
import com.zst.bluetooth.adapter.MsgAdapter;
import com.zst.bluetooth.bean.BlueMessage;
import com.zst.bluetooth.bean.BluetoothMsg;
import com.zst.bluetooth.task.ConnectTask;
import com.zst.bluetooth.task.OpenBlueTask;
import com.zst.bluetooth.utils.App;
import com.zst.bluetooth.utils.BlueToothUtils;
import com.zst.bluetooth.utils.TaskInfo;

import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MessageActivity extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener, MsgAdapter.OnItemBtnClickListener {

    private FloatingActionButton fab;

    public static final String DATE_PICKER_TAG = "date_picker";
    public static final String TIME_PICKER_TAG = "time_picker";

    private final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, DateTime.now().getYear(), DateTime.now().getMonthOfYear() - 1, DateTime.now().getDayOfMonth(), false);
    private final TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(this, DateTime.now().getHourOfDay(), DateTime.now().getMinuteOfHour(), true, false);
    private DateTime dateTime = new DateTime();
    private ArrayList<BlueMessage> msgList = new ArrayList<>();
    private String address = "";
    private MsgAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        //初始化toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitle("消息列表");

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);

        if (savedInstanceState != null) {
            //日期选择控件
            DatePickerDialog dpd = (DatePickerDialog) getSupportFragmentManager().findFragmentByTag(DATE_PICKER_TAG);
            if (dpd != null) {
                dpd.setOnDateSetListener(this);
            }

            //时间选择控件
            TimePickerDialog tpd = (TimePickerDialog) getSupportFragmentManager().findFragmentByTag(TIME_PICKER_TAG);
            if (tpd != null) {
                tpd.setOnTimeSetListener(this);
            }
        }

        address = BluetoothMsg.blueToothAddress;
        //获取已发送成功的所有的消息,按照时间排序
        msgList = App.getOrm().query(new QueryBuilder<>(BlueMessage.class)
                .where("belong = ?", new String[]{address}).orderBy("createTime"));
        RecyclerView list = (RecyclerView) findViewById(R.id.msg_list);
        list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        adapter = new MsgAdapter(this, msgList);
        adapter.setListener(this);
        list.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开启蓝牙连接线程
        OpenBlueTask task = new OpenBlueTask(address);
        task.setTaskInfo(new TaskInfo() {
            ProgressDialog pd = new ProgressDialog(MessageActivity.this);

            @Override
            public void onPre() {
                //显示对话框，提示用户
                pd.setCancelable(false);
                pd.setMessage("正在连接...");
                pd.show();
            }

            @Override
            public void onFinish(String result) {
                //隐藏对话框
                if (null != pd && pd.isShowing())
                    pd.dismiss();
                //如果连接失败,提示用户,退出此页面
                if (!result.equals("success")) {
                    Snackbar.make(fab, result, Snackbar.LENGTH_LONG).show();
                    finish();
                }
            }
        });
        //如果蓝牙没有连接,则连接蓝牙设备
        if (!BlueToothUtils.isOpen())
            task.start();
    }

    @Override
    public void onClick(View v) {
        if (v.equals(fab)) {
            //设置只可以输入从今往后3年的日期
            datePickerDialog.setYearRange(DateTime.now().getYear(), DateTime.now().getYear() + 3);
            //设置点击天之后直接结束
            datePickerDialog.setCloseOnSingleTapDay(true);
            //显示日期选择对话框
            datePickerDialog.show(getSupportFragmentManager(), DATE_PICKER_TAG);
        }
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        dateTime = new DateTime(year, month + 1, day, 0, 0, 0);
        if (dateTime.plusDays(1).isBeforeNow()) {//如果选择的日期早于当前日期,提示用户
            Snackbar.make(fab, "不能早于当前日期，请重新选择", Snackbar.LENGTH_LONG).show();
            datePickerDialog.dismiss();//关闭当前日期选择器
            this.datePickerDialog.show(getSupportFragmentManager(), DATE_PICKER_TAG);//重新打开
        } else {
            //否则设置时间选择器,默认时间为当前时间
            timePickerDialog.setStartTime(DateTime.now().getHourOfDay(), DateTime.now().getMinuteOfHour());
            //显示时间对话框
            timePickerDialog.show(getSupportFragmentManager(), TIME_PICKER_TAG);
        }
    }

    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        dateTime = dateTime.plusHours(hourOfDay).plusMinutes(minute);
        if (dateTime.isBeforeNow()) {
            Snackbar.make(fab, "不能早于当前时间，请重新选择", Snackbar.LENGTH_LONG).show();
            timePickerDialog.dismiss();
            timePickerDialog.show(getSupportFragmentManager(), TIME_PICKER_TAG);
        } else {
            //新建一条消息
            BlueMessage msg = new BlueMessage();
            msg.createTime = dateTime.getMillis();
            msg.state = BlueMessage.State.STATE_PRE_SEND;
            msg.type = BlueMessage.Type.TYPE_TASK;
            msg.belong = address;
            msg.sender = BluetoothMsg.blueToothName;
            msgList.add(msg);
            //进行排序
            Collections.sort(msgList, new SortByTime());
            //相应适配器
            adapter.notifyDataSetChanged();
            //这行代码用于百度统计,代码中类似的代码都是用于百度统计的
            StatService.onEvent(this, "add", "新建任务");
        }
    }

    /**
     * item消息点击事件
     *
     * @param msg 对应的消息
     */
    @Override
    public void onClick(final BlueMessage msg) {
        boolean canSend = false;
        //判断消息状态,如果是发送前或者是发送失败,则可以发送
        switch (msg.state) {
            case STATE_PRE_SEND:
            case STATE_SEND_FAIL:
                canSend = true;
                break;
        }
        //发送消息线程
        ConnectTask task = new ConnectTask("NOTE:" + msg.content + "#" + new DateTime(msg.createTime).toString("YYYY-MM-dd HH:mm"));
        task.setTaskInfo(new TaskInfo() {
            @Override
            public void onPre() {
                //要发送时,将消息状态设置为发送中
                msg.state = BlueMessage.State.STATE_SENDING;
                notifyData();
                StatService.onEvent(MessageActivity.this, "send_note", "开始发送");
            }

            @Override
            public void onFinish(String result) {
                //对发送结果进行判断.
                if (result.equals("success")) {
                    //如果发送成功,将消息的状态改为发送成功,将此条消息存入数据库
                    msg.state = BlueMessage.State.STATE_SEND_SUCCESS;
                    App.getOrm().save(msg);//将消息存入数据库
                    StatService.onEvent(MessageActivity.this, "send_note_success", "发送成功");
                } else {
                    //如果发送失败,将消息的状态改为发送失败,并提示用户
                    msg.state = BlueMessage.State.STATE_SEND_FAIL;
                    StatService.onEvent(MessageActivity.this, "send_note_fail", "发送失败");
                    if (!result.equals("fail"))
                        Snackbar.make(fab, result, Snackbar.LENGTH_LONG).show();
                }
                //更新页面
                notifyData();
            }
        });
        //如果可以发送,则执行发送线程
        if (canSend)
            task.start();
    }

    private void notifyData() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 按照时间排序
     */
    public class SortByTime implements Comparator<BlueMessage> {

        @Override
        public int compare(BlueMessage lhs, BlueMessage rhs) {
            DateTime l = new DateTime(lhs.createTime);
            DateTime r = new DateTime(rhs.createTime);
            if (l.isAfter(r)) {
                return 1;
            } else {
                return -1;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }
}